<!--
 * @Author: wwssaabb
 * @Date: 2021-07-21 09:35:45
 * @LastEditTime: 2021-07-21 10:11:12
 * @FilePath: \demo\react_demo\demo\base_demo\getSnapshotBeforeUpdate.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .list{
      width: 200px;
      height: 150px;
      background-color: skyblue;
      overflow: auto;
    }
    .news{
      height: 30px;
    }
  </style>
</head>
<body>
  <div id="test"></div>

  <script type="text/javascript" src="../js/react.development.js" ></script>
  <script type="text/javascript" src="../js/react-dom.development.js" ></script>
  <script type="text/javascript" src="../js/babel.min.js" ></script>
  <script type="text/javascript" src="../js/prop-types.js" ></script>
  <script type="text/babel">  /* JSX 语法用babel转换 */

    class Demo extends React.Component{

      state={
        list:[]
      }

      render(){
        console.log('render')
        return (
          <div className="list" ref='list'>
            {
              this.state.list.map((i,index)=>{
                return <div className="news" key={index}>{i}</div>
              })
            }
          </div>
        )
      }

      getSnapshotBeforeUpdate(){
        console.log('getSnapshotBeforeUpdate')
        return this.refs.list.scrollHeight
      }

      componentDidUpdate(prevProps,prevState,snapshot){
        console.log('componentDidUpdate')
        console.log('snapshot',snapshot)
        this.refs.list.scrollTop +=this.refs.list.scrollHeight-snapshot
      }

      componentDidMount(){
        setInterval(()=>{
          const {list} =this.state
          const news = '新闻'+(list.length+1)
          this.setState({list:[news,...list]})
        },1000)
      }

    }
    
    ReactDOM.render(<Demo/>,document.getElementById('test'))

  </script>
</body>
</html>